/**
 * Copyright (C) 2020-2022
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
import __config from 'config/env';
import util from 'utils/util';

const request = (url, method, data, showLoading) => {
	let _url = url;
	//#ifndef H5
	_url = __config.basePath + url
	//#endif
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading();
		}
		uni.request({
			url: _url,
			method: method,
			data: data,
			withCredentials: true,
			header: {
				//#ifdef H5
				'client-type': util.isWeiXinBrowser() ? 'H5-WX' : 'H5', //客户端类型普通H5或微信H5
				'tenant-id': getApp().globalData.tenantId,
				'app-id': getApp().globalData.appId ? getApp().globalData.appId : '', //微信h5有appId
				//#endif
				//#ifdef MP-WEIXIN
				'client-type': 'MA', //客户端类型小程序
				'app-id': uni.getAccountInfoSync().miniProgram.appId, //小程序appId
				//#endif
				//#ifdef APP-PLUS
				'client-type': 'APP', //客户端类型APP
				'tenant-id': getApp().globalData.tenantId,
				//#endif
				'third-session': uni.getStorageSync('third_session') ? uni.getStorageSync(
					'third_session') : '',
			},
			success(res) {
				if (showLoading) {
					uni.hideLoading();
				}
				if (res.statusCode == 200) {
					if (res.data.code != 0) {
						if (res.data.code == 60001 || res.data.code == 60002) {
							// 心跳接口不处理
							if (_url.indexOf('useronline/heartbeat') != -1) {
								// 不做处理
							} else
							if (!getApp().globalData.logining) {
								getApp().globalData.logining = true //防止同时多个接口触发登录
								if (util.isMiniPg() || (getApp().globalData.appId && util
										.isWeiXinBrowser())) {
									//小程序或公众号H5，删除third_session重新登录
									uni.removeStorageSync('third_session');
									getApp().doLogin().then(res => {
										var pages = getCurrentPages(); // 获取页面栈
										var currPage = pages[pages.length - 1]; // 当前页面
										currPage.onLoad(currPage.options)
										currPage.onShow()
									});
								} else {
									util.backLoginPage()
								}
								setTimeout(function() {
									getApp().globalData.logining = false;
								}, 2000);
							}
							reject("session过期重新登录");
						} else if (res.data.code == 60003) {
							if (!getApp().globalData.logining2) {
								getApp().globalData.logining2 = true //防止同时多个接口触发登录
								util.backLoginPage()
								setTimeout(function() {
									getApp().globalData.logining2 = false;
								}, 2000);
							}
							reject("请先登录商城");
						} else {
							if (res.data.errCode || res.data.errCode == 0) {
								//兼容im返回
								resolve(res.data);
							} else {
								let errMsg = res.data.msg || res.errMsg
								uni.showToast({
									icon: 'none',
									title: errMsg + '',
									duration: 3000
								})
								reject(res.data.msg);
							}
						}
					}
					resolve(res.data);
				} else if (res.statusCode == 404) {
					uni.showToast({
						icon: 'none',
						title: '接口请求出错，请检查手机网络',
						duration: 3000
					})
					reject();
				} else if (res.statusCode == 502) {
					// console.log(502)
					uni.showToast({
						icon: 'none',
						title: '服务器维护中，请稍后再来',
						duration: 3000
					})
					reject();
				} else if (res.statusCode == 503) {
					console.log(503)
					uni.showToast({
						title: '503错误，服务未启动',
						icon: 'none',
						duration: 3000
					})
					reject();
				} else {
					// uni.showModal({
					//     title: '提示',
					//     content: '错误：' + res.data.msg,
					//     success(res) {
					//     }
					// });
					// reject(res);
					reject();
				}
			},
			fail(error) {
				//3提示无网络
				if (showLoading) {
					uni.hideLoading();
				}
				if (error.errMsg && error.errMsg.indexOf('statusCode:-1') != -1) {
					console.log("无网络");
				} else
				if (getApp().globalData.hasNetwork) {
					// 忽略该错误 带有interrupted的 一般都是小程序切后台中断导致的 https://zhuanlan.zhihu.com/p/453875594
					let ignoreErrMsg = 'network api interrupted in suspend state'
					if (error.errMsg) {
						if (error.errMsg.indexOf('network api interrupted in suspend state') == -
							1) {
							uni.showToast({
								icon: 'none',
								title: '接口请求出错：' + error.errMsg,
								duration: 3000
							})
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '接口请求出错：' + error,
							duration: 3000
						})
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: '无法连接到网络'
					})
				}
				reject(error);
			}
		});
	});
};

// 登录成功后需要进行的统一操作
const loginSuccess = (request) => {
	return new Promise((resolve, reject) => {
		request.then((res) => {
			if (res && res.data.id) { // 登录成功
				console.log("************登录成功************");
				let userInfo = res.data;
				uni.setStorageSync('third_session', userInfo.thirdSession);
				uni.setStorageSync('user_info', userInfo);
				if (getApp().globalData.userOnlineTimer) {
					clearInterval(getApp().globalData.userOnlineTimer)
					getApp().globalData.userOnlineTimer = null
				}
				getApp().userOnlineHeartbeat()
			}
			resolve(res)
		}).catch((err) => {
			reject(err)
		})
	})
}

// 退出登录后需要进行的统一操作
const logoutSuccess = (request) => {
	return new Promise((resolve, reject) => {
		request.then((res) => {
			//退出登录成功
			console.log("************退出登录成功************");
			getApp().userOnlineHeartbeat(true)
			resolve(res)
		}).catch((err) => {
			reject(err)
		})
	})
}

/**
 * 上传文件接口
 * @param {Object} filePath 本地文件路径
 * @param {Object} dir 上传保存的文件目录, 如头像保存的目录: headimg/
 * @param {Object} fileType 文件类型说明(没有强制要求) image/video/file/...
 */
function uploadFile(filePath, dir, fileType) {
	// 上传文件
	let _url = '/mallapi/file/upload';
	//#ifndef H5
	_url = __config.basePath + _url;
	//#endif
	let that = this;
	uni.showLoading({
		title: '上传中'
	});
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			header: {
				//#ifdef H5
				'client-type': util.isWeiXinBrowser() ? 'H5-WX' : 'H5', //客户端类型普通H5或微信H5
				'tenant-id': getApp().globalData.tenantId,
				'app-id': getApp().globalData.appId ? getApp().globalData.appId : '', //微信h5有appId
				//#endif
				//#ifdef MP-WEIXIN
				'client-type': 'MA', //客户端类型小程序
				'app-id': uni.getAccountInfoSync().miniProgram.appId, //小程序appId
				//#endif
				//#ifdef APP-PLUS
				'client-type': 'APP', //客户端类型APP
				'tenant-id': getApp().globalData.tenantId,
				//#endif
				'third-session': uni.getStorageSync('third_session') ? uni.getStorageSync(
					'third_session') : '',
			},
			url: _url,
			filePath: filePath,
			name: 'file',
			formData: {
				fileType: fileType,
				dir: dir
			},
			success: (uploadFileRes) => {
				uni.hideLoading();
				if (uploadFileRes.statusCode == '200') {
					let link = JSON.parse(uploadFileRes.data).link;
					resolve(link)
				} else {
					uni.showModal({
						title: "提示",
						content: "上传失败:" + uploadFileRes.data,
						success(res) {}
					});
					reject()
				}
			},
			fail: (err) => {
				uni.hideLoading();
				console.log(err);
				reject()
			}
		});
	})
}
module.exports = {
	request,
	uploadFile,
	loginWxMa: data => {
		//如果有分享人则带上分享人的user_code
		data = util.dataAddSharerUserCode(data)
		//微信小程序登录接口
		// return request('/mallapi/wxuser/loginma', 'post', data, false);
		return loginSuccess(request('/mallapi/wxuser/loginma', 'post', data, false));
	},
	loginWxMp: data => {
		//如果有分享人则带上分享人的user_code
		data = util.dataAddSharerUserCode(data)
		//微信公众号登录接口
		return loginSuccess(request('/mallapi/wxuser/loginmp', 'post', data, false));
	},
	loginByPhoneMa: data => {
		//如果有分享人则带上分享人的user_code
		data = util.dataAddSharerUserCode(data)
		//商城通过小程序授权手机号一键登录商城
		return loginSuccess(request('/mallapi/userinfo/ma/phone/login', 'post', data, true));
	},
	loginByPhone: data => {
		//如果有分享人则带上分享人的user_code
		data = util.dataAddSharerUserCode(data)
		//商城手机验证码登录商城
		return loginSuccess(request('/mallapi/userinfo/phone/login', 'post', data, true));
	},
	login: data => {
		//如果有分享人则带上分享人的user_code
		data = util.dataAddSharerUserCode(data)
		//商城账号登录
		return loginSuccess(request('/mallapi/userinfo/login', 'post', data, true));
	},
	logout: data => {
		//商城退出登录
		return logoutSuccess(request('/mallapi/userinfo/logout', 'post', data, true));
	},
	getPhoneCode: data => {
		//获取手机验证码
		return request('/mallapi/phone/code', 'get', data, true);
	},
	register: data => {
		//如果有分享人则带上分享人的user_code
		data = util.dataAddSharerUserCode(data)
		//账号注册
		return request('/mallapi/userinfo/register', 'post', data, true);
	},
	updateUserPhone: data => {
		//修改商城用户手机号
		return request('/mallapi/userinfo/phone', 'post', data, true);
	},
	getJsSdkConfig: data => {
		//获取jssdk config参数
		return request('/mallapi/wxjssdk/config', 'post', data, false);
	},
	themeMobileGet: () => {
		//获取商城主题装修配置
		return request('/mallapi/thememobile', 'get', null, false);
	},
	shopInfoPage: data => {
		//店铺列表
		return request('/mallapi/shopinfo/page', 'get', data, false);
	},
	shopInfoPageWithSpu: data => {
		//店铺列表带商品
		return request('/mallapi/shopinfo/pagewithspu', 'get', data, false);
	},
	shopInfoGet: id => {
		//店铺查询
		return request('/mallapi/shopinfo/' + id, 'get', null, false);
	},
	shopStorePage: data => {
		//门铺列表
		return request('/mallapi/shopstore/page', 'get', data, false);
	},
	shopStoreGet: id => {
		// 店铺门店查询
		return request('/mallapi/shopstore/' + id, 'get', null, false);
	},
	userInfoUpdateByMa: data => {
		//通过微信小程序更新用户信息
		return request('/mallapi/userinfo/ma', 'put', data, true);
	},
	userInfoUpdateByMp: data => {
		//通过微信公众号网页授权更新用户信息
		return request('/mallapi/userinfo/mp', 'put', data, true);
	},
	goodsCategoryTree: data => {
		//商城商品分类tree查询
		return request('/mallapi/goodscategory/tree', 'get', data, false);
	},
	goodsCategoryShopTree: data => {
		//店铺商品分类tree查询
		return request('/mallapi/goodscategoryshop/tree', 'get', data, true);
	},
	goodsPage: data => {
		//商品列表
		return request('/mallapi/goodsspu/page', 'get', data, false);
	},
	goodsGet: id => {
		//商品查询
		return request('/mallapi/goodsspu/' + id, 'get', null, false);
	},
	goodsSpecGet: data => {
		//商品规格查询
		return request('/mallapi/goodsspuspec/tree', 'get', data, true);
	},
	shoppingCartPage: data => {
		//购物车列表
		return request('/mallapi/shoppingcart/page', 'get', data, false);
	},
	shoppingCartAdd: data => {
		//购物车新增
		return request('/mallapi/shoppingcart', 'post', data, true);
	},
	shoppingCartUpdate: data => {
		//购物车修改
		return request('/mallapi/shoppingcart', 'put', data, true);
	},
	shoppingCartDel: data => {
		//购物车删除
		return request('/mallapi/shoppingcart/del', 'post', data, false);
	},
	shoppingCartCount: data => {
		//购物车数量
		return request('/mallapi/shoppingcart/count', 'get', data, false);
	},
	orderSub: data => {
		//订单提交
		return request('/mallapi/orderinfo', 'post', data, true);
	},
	orderPage: data => {
		//订单列表
		return request('/mallapi/orderinfo/page', 'get', data, false);
	},
	orderGet: id => {
		//订单详情查询
		return request('/mallapi/orderinfo/' + id, 'get', null, false);
	},
	orderCancel: id => {
		//订单确认取消
		return request('/mallapi/orderinfo/cancel/' + id, 'put', null, true);
	},
	orderReceive: id => {
		//订单确认收货
		return request('/mallapi/orderinfo/receive/' + id, 'put', null, true);
	},
	orderDel: id => {
		//订单删除
		return request('/mallapi/orderinfo/' + id, 'delete', null, false);
	},
	orderCountAll: data => {
		//订单计数
		return request('/mallapi/orderinfo/countAll', 'get', data, false);
	},
	orderLogisticsGet: logisticsId => {
		//订单物流查询
		return request('/mallapi/orderinfo/orderlogistics/' + logisticsId, 'get', null, false);
	},
	unifiedOrder: data => {
		//下单接口
		return request('/mallapi/orderinfo/unifiedOrder', 'post', data, true);
	},
	userAddressPage: data => {
		//用户收货地址列表
		return request('/mallapi/useraddress/page', 'get', data, false);
	},
	userAddressSave: data => {
		//用户收货地址新增
		return request('/mallapi/useraddress', 'post', data, true);
	},
	userAddressDel: id => {
		//用户收货地址删除
		return request('/mallapi/useraddress/' + id, 'delete', null, false);
	},
	userCollectAdd: data => {
		//用户收藏新增
		return request('/mallapi/usercollect', 'post', data, true);
	},
	userCollectDel: id => {
		//用户收藏删除
		return request('/mallapi/usercollect/' + id, 'delete', null, false);
	},
	userCollectPage: data => {
		//用户收藏列表
		return request('/mallapi/usercollect/page', 'get', data, false);
	},
	userFootprintPage: data => {
		//用户足迹列表
		return request('/mallapi/userfootprint/page', 'get', data, false);
	},
	goodsAppraisesAdd: data => {
		//商品评价新增
		return request('/mallapi/goodsappraises', 'post', data, true);
	},
	goodsAppraisesPage: data => {
		//商品评价列表
		return request('/mallapi/goodsappraises/page', 'get', data, false);
	},
	qrCodeUnlimited: data => {
		//获取小程序二维码
		return request('/mallapi/wxqrcode/unlimited', 'post', data, true);
	},
	orderItemGet: id => {
		//查询订单详情
		return request('/mallapi/orderitem/' + id, 'get', null, false);
	},
	orderRefundsSave: data => {
		//发起退款
		return request('/mallapi/orderrefunds', 'post', data, true);
	},
	orderRefundsUpdate: (data) => {
		//修改退款详情
		return request("/mallapi/orderrefunds", "put", data, true);
	},
	userInfoGet: () => {
		//查询商城用户信息
		return request('/mallapi/userinfo', 'get', null, false);
	},
	userInfoUpdate: (data) => {
		//修改商城用户
		return request('/mallapi/userinfo', 'put', data, true);
	},
	pointsRecordPage: data => {
		//查询积分记录
		return request('/mallapi/pointsrecord/page', 'get', data, false);
	},
	pointsConfigGet: () => {
		//查询积分配置
		return request('/mallapi/pointsconfig', 'get', null, false);
	},
	couponUserSave: data => {
		//电子券用户领取
		return request('/mallapi/couponuser', 'post', data, true);
	},
	couponUserPage: data => {
		//电子券用户列表
		return request('/mallapi/couponuser/page', 'get', data, false);
	},
	couponInfoPage: data => {
		//电子券列表
		return request('/mallapi/couponinfo/page', 'get', data, false);
	},
	bargainInfoPage: data => {
		//砍价列表
		return request('/mallapi/bargaininfo/page', 'get', data, false);
	},
	bargainInfoGet: data => {
		//砍价详情
		return request('/mallapi/bargaininfo', 'get', data, true);
	},
	bargainUserSave: data => {
		//发起砍价
		return request('/mallapi/bargainuser', 'post', data, true);
	},
	bargainCutPage: data => {
		//帮砍记录
		return request('/mallapi/bargaincut/page', 'get', data, true);
	},
	bargainUserGet: id => {
		//砍价记录详情
		return request('/mallapi/bargainuser/' + id, 'get', null, false);
	},
	bargainUserPage: data => {
		//砍价记录列表
		return request('/mallapi/bargainuser/page', 'get', data, true);
	},
	bargainCutSave: data => {
		//砍一刀
		return request('/mallapi/bargaincut', 'post', data, true);
	},
	listEnsureBySpuId: data => {
		//通过spuID，查询商品保障
		return request('/mallapi/ensuregoods/listEnsureBySpuId', 'get', data, true);
	},
	grouponInfoPage: data => {
		//拼团列表
		return request('/mallapi/grouponinfo/page', 'get', data, false);
	},
	grouponInfoGet: id => {
		//拼团详情
		return request('/mallapi/grouponinfo/' + id, 'get', null, true);
	},
	grouponUserPageGrouponing: data => {
		//拼团中分页列表
		return request('/mallapi/grouponuser/page/grouponing', 'get', data, true);
	},
	grouponUserPage: data => {
		//拼团记录列表
		return request('/mallapi/grouponuser/page', 'get', data, true);
	},
	grouponUserGet: id => {
		//拼团记录详情
		return request('/mallapi/grouponuser/' + id, 'get', null, false);
	},

	seckillhallList: date => {
		//秒杀会场时间列表
		return request('/mallapi/seckillhall/list?hallDate=' + date, 'get', null, false);
	},
	seckillinfoPage: data => {
		//秒杀列表
		return request('/mallapi/seckillinfo/page', 'get', data, false);
	},
	seckillInfoGet: (seckillHallInfoId) => {
		//秒杀详情
		return request('/mallapi/seckillinfo/' + seckillHallInfoId, 'get', null, true);
	},
	wxTemplateMsgList: data => {
		//订阅消息列表
		return request('/mallapi/wxtemplatemsg/list', 'post', data, false);
	},
	liveRoomInfoList: data => {
		//获取直播房间列表
		return request('/mallapi/wxmalive/roominfo/list', 'get', data, true);
	},
	customerServiceList: shopId => {
		//客服列表
		return request('/mallapi/customerservice/list/' + shopId, 'get', null, false);
	},
	pagedevise: pageType => {
		//首页组件配置
		return request('/mallapi/pagedevise?pageType=' + pageType, 'get', null, false);
	},
	pagedeviseShop: shopId => {
		// 店铺组件配置
		return request('/mallapi/pagedevise?pageType=2&shopId=' + shopId, 'get', null, false);
	},
	articlePage: data => {
		//文章列表
		return request('/mallapi/articleinfo/page', 'get', data, false);
	},
	articleGet: id => {
		//文章详情
		return request('/mallapi/articleinfo/' + id, 'get', null, false);
	},
	articleCategoryPage: data => {
		//文章分类列表
		return request('/mallapi/articlecategory/page', 'get', data, false);
	},
	userSign: data => {
		//积分签到
		return request('/mallapi/signrecord/user', 'post', data, false);
	},
	getSignRecord: data => {
		//签到记录查询
		return request('/mallapi/signrecord/user', 'get', data, false);
	},
	signConfigPage: data => {
		//获取签到积分记录
		return request('/mallapi/signconfig/page', 'get', data, false);
	},
	distributionConfig: () => {
		//分销设置查询
		return request('/mallapi/distributionconfig', 'get');
	},
	distributionuser: () => {
		//分销员查询
		return request('/mallapi/distributionuser', 'get');
	},
	distributionuserPage: (data) => {
		//分销员查询
		return request('/mallapi/distributionuser/page', 'get', data);
	},
	distributionorderPage: data => {
		//分销订单分页
		return request('/mallapi/distributionorder/page', 'get', data);
	},
	distributionorderFrozenAmount: data => {
		//获取当前分销员的冻结金额
		return request('/mallapi/distributionorder/frozenAmount', 'get', data);
	},
	distributionPromotionPage: data => {
		//分销 推广人统计
		return request('/mallapi/userinfo/page', 'get', data);
	},
	userwithdrawRecordSave: data => {
		//分销 申请提现
		return request('/mallapi/userwithdrawrecord', 'post', data, true);
	},
	userwithdrawRecordUpdate: data => {
		//分销 提现申请修改
		return request('/mallapi/userwithdrawrecord', 'put', data, true);
	},
	userwithdrawRecordPage: data => {
		//分销 提现记录
		return request('/mallapi/userwithdrawrecord/page', 'get', data);
	},
	userwithdrawRecord: id => {
		//分销 提现记录详情
		return request('/mallapi/userwithdrawrecord/' + id, 'get', null);
	},
	userRecord: () => {
		//分销 用户消费总额记录
		return request('/mallapi/userrecord', 'get', null);
	},
	wxAppConfig: id => {
		//获取wx一件授权的component_appid
		return request('/mallapi/wxapp/' + id, 'get', null);
	},
	userAppraisesPage: data => {
		//我的评价
		return request('/mallapi/goodsappraises/page/user', 'get', data);
	},
	goodsSpuListByIds: data => {
		//根据id集合商品查询
		if (data && data.length > 0) {
			return request('/mallapi/goodsspu/listbyids', 'post', data, false);
		} else {
			return new Promise((resolve, reject) => {
				resolve({
					data: []
				})
			})
		}
	},
	userOnlineHeartbeat: data => {
		// 接收商城用户心跳
		return request('/mallapi/useronline/heartbeat', 'get', data);
	},
	shopApply: data => {
		// 店铺入驻——店铺信息验证
		return request('/mall/shopapply/addedit', 'put', data);
	},
	shopApplyQuery: data => {
		// 店铺入驻——根据编号(id)查询
		return request('/mall/shopapply/one', 'get', data);
	},
	shopApplyShopInfoValidate: data => {
		// 店铺入驻——店铺信息验证
		return request('/mall/shopinfo/count', 'get', data);
	},
	shopApplyLoginUserValidate: data => {
		// 店铺入驻——店长登录账号信息验证
		return request('/upms/user/count', 'get', data);
	},
	imLogin: data => {
		//im 登录
		return request('/mallapi/im/login', 'post', data, false);
	},
	imRegister: data => {
		//im 注册
		return request('/mallapi/im/register', 'post', data, false);
	},
	indexTotal: data => {
		//im 注册
		// return request('/agentmerchantapi/index/total', 'put', data, false); 
	},
};